package com.example.demo.dao;

import com.example.demo.bean.Building;
import com.example.demo.bean.Gonggao;
import com.example.demo.bean.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class ProductDao {
    @Autowired
    JdbcTemplate template;

    public int getCount() {
        int count = template.queryForObject("select count(*) from product", Integer.class);
        return count;
    }

    public int addProduct(Product product) {
        return template.update("insert into product values (null,?,?,?,?)",
                product.getName(),product.getDescription(),product.getUnit_price(),product.getStock_quantity());
    }

    public int updateProduct(Product product) {
        return template.update("update product set name = ?, description = ?,unit_price = ?,stock_quantity = ? where id = ?",
                product.getName(),product.getDescription(),product.getUnit_price(),product.getStock_quantity(),product.getId());
    }

    public int delProduct(int id) {
        return template.update("delete from product where id = ?",id);
    }

    public List<Product> getAllProducts(int page, int limit) {
        List<Product> list = template.query("select * from Product limit ?,?", new Object[]{(page - 1) * limit, limit},
                new BeanPropertyRowMapper(Product.class));
        if (!list.isEmpty()){
            return list;
        } else {
            return null;
        }
    }
    public int getCount(String name) {
        int count = template.queryForObject("select count(*) from product where name like '%"+name+"%' ", Integer.class);
        return count;
    }
    public List<Product> findProductByName(int page, int limit ,String name){
        List<Product> list = template.query("select * from product where name like '%"+name+"%' limit ?,?" ,new Object[]{(page-1)*limit,limit},
                new BeanPropertyRowMapper(Product.class));
        if (list!=null){
            return list;
        }else{
            return null;
        }
    }

    public List<Product> getAllProducts() {
        List<Product> list = template.query("select * from product",
                new BeanPropertyRowMapper(Product.class));
        if (list!=null){
            return list;
        }else{
            return null;
        }
    }


}
